﻿using System;
using System.IO;
using System.Security;
using System.Web;
using SnippetBox.Core.Common.Utilities;

namespace SnippetBox.Core.Infrastructure {
    public class SettingsWatcher {

        public static void Init() {
            var trustUtility = new TrustUtility();
            var hasFullTrust = trustUtility.HasTrustLevel(AspNetHostingPermissionLevel.High);

            if (hasFullTrust) {
                string path = Path.GetDirectoryName(Settings.Current.SettingsPath);
                string fileName = Path.GetFileName(Settings.Current.SettingsPath);

                if (path == null || fileName == null)
                    return;

                StartFileWatcher(path, fileName);
            }

            // initialize settings for the first time
            Settings.Current.LoadChanges();
        }

        public static void StartFileWatcher(string path, string fileName) {
            FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
            FileSystemEventHandler loadChangesHandler = (sender, e) => {
                // update only if it was more than 2 seconds since last change
                if (Settings.Current.LastChanged == DateTime.MinValue
                        || DateTime.Now.Subtract(Settings.Current.LastChanged).TotalSeconds > 2)
                    Settings.Current.LoadChanges();
            };

            fileSystemWatcher = new FileSystemWatcher(path, fileName);
            fileSystemWatcher.Created += loadChangesHandler;
            fileSystemWatcher.Changed += loadChangesHandler;

            fileSystemWatcher.EnableRaisingEvents = true;
        }
    }
}
